package bb.lanxing.lib.devices.bryton.bbcp;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
//import com.alipay.sdk.util.e;
import bb.lanxing.lib.devices.bryton.bbcp.BBDeviceAdapter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.TreeMap;
import java.util.UUID;

@SuppressLint("MissingPermission")
public class BBDevice implements DfuManagerCallbacks, BbcpManagerCallbacks {
    public static final int ACTION_ABORT = 17;
    public static final int ACTION_BIND = 7;
    private static final int ACTION_BUSY = -2;
    public static final int ACTION_CONNECT = 0;
    public static final int ACTION_DISCONNECT = 1;
    public static final int ACTION_LIVE_DATA = 4;
    private static final int ACTION_NONE = -1;
    public static final int ACTION_READ_DEVICE_INFO = 6;
    public static final int ACTION_READ_DEVICE_STATE = 12;
    public static final int ACTION_READ_LOG_DATA = 10;
    public static final int ACTION_READ_LOG_FILE = 14;
    public static final int ACTION_READ_LOG_FILE_LIST = 13;
    public static final int ACTION_READ_PROFILE = 15;
    public static final int ACTION_REFRESH_DATA = 5;
    public static final int ACTION_UPDATE_SOFTWARE = 2;
    public static final int ACTION_WRITE_ALARM = 9;
    public static final int ACTION_WRITE_PROFILE = 8;
    public static final int ACTION_WRITE_SERVEREE = 16;
    public static final int ACTION_WRITE_SYNC_TIME = 11;
    public static final int ACTION_WRITE_USER_ADDRESS = 3;
    public static final int BBCP_READ_MORE_DATA = 1;
    public static final int BBCP_SUCCESS = 0;
    private static final String BBDEVICE_BROADCAST_CONNECTION = "com.brytonsport.bbcp.BBDEVICE_BROADCAST_CONNECTION";
    private static final String BBDEVICE_BROADCAST_PROGRESS = "com.brytonsport.bbcp.BBDEVICE_BROADCAST_PROGRESS";
    static final String BBDEVICE_BROADCAST_SCAN = "com.brytonsport.bbcp.BBDEVICE_BROADCAST_SCAN";
    static final String BOOTLOADER_NAME = "DfuTarg";
    private static final String EXTRA_ACTION = "action";
    private static final String EXTRA_ACTION_TYPE = "action.type";
    static final String EXTRA_CONNECTION_STATE = "connection.state";
    private static final String EXTRA_DATA = "status";
    static final String EXTRA_DEVICE_ADDRESS = "address";
    static final String EXTRA_DEVICE_NAME = "name";
    static final String EXTRA_DEVICE_RSSI = "rssi";
    static final String EXTRA_DEVICE_SCAN_RECORD = "scanRecord";
    public static final int STATE_CLOSED = -5;
    public static final int STATE_CONNECTED = -2;
    public static final int STATE_CONNECTED_AND_READY = -3;
    public static final int STATE_CONNECTING = -1;
    public static final int STATE_DISCONNECTED = 0;
    public static final int STATE_DISCONNECTING = -4;
    private static final String TAG = "BBDevice";
    private BBDeviceAdapter mAdapter;
    private volatile Handler mAsyncHandler;
    private volatile Looper mAsyncLooper;
    private BbcpManager mBbcpManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mBluetoothDevice;
    private BluetoothGatt mBluetoothGatt;
    private BluetoothManager mBluetoothManager;
    private String mCapability;
    private Context mContext;
    private byte[] mCurData;
    private BBDeviceCallbacks mDeviceCallback;
    private boolean mDeviceDiscovered;
    private DfuManager mDfuManager;
    private int mErrorState;
    private String mModel;
    private byte[] mResponse;
    private byte mSeqNo;
    private String mUuid;
    private String mVersion;
    private static final UUID CLIENT_CHARACTERISTIC_CONFIG = new UUID(45088566677504L, -9223371485494954757L);
    private static BBDevice sConnectedDevice = null;
    private static boolean mNeedScan = true;
    private short mReadPacketsOfFlowControl = 10;
    private short mWritePacketsOfFlowControl = 5;
    private final Object mLock = new Object();
    private boolean mNotificationsEnabled = false;
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bArr) {
        }
    };
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] bArr;
            BBDevice.this.logi("BBDevice onReceive");
            String action = intent.getAction();
            if (BBDevice.BBDEVICE_BROADCAST_CONNECTION.equals(action)) {
                int intExtra = intent.getIntExtra(BBDevice.EXTRA_CONNECTION_STATE, 0);
                BBDevice bBDevice = BBDevice.this;
                bBDevice.handleConnectionStateChanged(bBDevice.mBluetoothGatt, intExtra);
            } else if (!BBDevice.BBDEVICE_BROADCAST_PROGRESS.equals(action)) {
            } else {
                int intExtra2 = intent.getIntExtra("action", 0);
                int intExtra3 = intent.getIntExtra("status", 0);
                BBDevice bBDevice2 = BBDevice.this;
                bBDevice2.logi("receive action=" + intExtra2 + ",result=" + intExtra3 + ",mAction=" + BBDevice.this.mAction);
                if (intExtra2 == -1) {
                    BBDevice.this.logi("onReceive: connectStateChanged");
                    BBDevice.this.mDeviceCallback.onStateChanged(BBDevice.this.mConnectionState);
                    int unused = BBDevice.this.mConnectionState;
                } else if (intExtra2 == 0) {
                    if (BBDevice.this.mAction == 0) {
                        BBDevice.this.logi("onConnectCompleted");
                        BBDevice.this.mAction = -1;
                        BBDevice.this.mDeviceCallback.onConnectCompleted(intExtra3);
                        return;
                    }
                    BBDevice.this.loge("connect state is not consistent");
                    BBDevice.this.mDeviceCallback.onStateChanged(BBDevice.this.mConnectionState);
                } else if (intExtra2 == 1) {
                    BBDevice.this.logi("onDisconnectCompleted");
                    BBDevice.this.mAction = -1;
                    BBDevice.this.mDeviceCallback.onDisconnectCompleted(intExtra3);
                } else if (intExtra2 == 4) {
                    if (BBDevice.this.mAction != 4) {
                        return;
                    }
                    BBDevice.this.mAction = -1;
                    BBDevice.this.mDeviceCallback.onLiveDataEnabled(intExtra3, BBDevice.this.mNotificationsEnabled);
                } else if (intExtra2 == 5) {
                    if (!BBDevice.this.mNotificationsEnabled) {
                        return;
                    }
                    synchronized (BBDevice.this.mLock) {
                        bArr = new byte[BBDevice.this.mCurData.length];
                        System.arraycopy(BBDevice.this.mCurData, 0, bArr, 0, BBDevice.this.mCurData.length);
                    }
                    BBDevice.this.mDeviceCallback.onLiveDataChanged(bArr);
                } else if (intExtra2 != 7) {
                    if (intExtra3 != 270 && intExtra3 != 256) {
                        return;
                    }
                    if (intent.getIntExtra(BBDevice.EXTRA_ACTION_TYPE, 0) == ActionType.ACTION_READ.intValue()) {
                        BBDevice.this.mDeviceCallback.onDataRead(intExtra2, intExtra3, null, null);
                    } else {
                        BBDevice.this.mDeviceCallback.onDataWrite(intExtra2, intExtra3);
                    }
                } else if (BBDevice.this.mAction != 3 && BBDevice.this.mAction != 6 && BBDevice.this.mAction != 7) {
                } else {
                    BBDevice.this.mAction = -1;
                    BBDevice.this.logi("onBonded() is called");
                    BBDevice.this.mDeviceCallback.onBonded(intExtra3);
                }
            }
        }
    };
    private BBDeviceAdapter.ScanDeviceCallbacks scanCallbacks = new BBDeviceAdapter.ScanDeviceCallbacks() {
        @Override
        public void onScanDevice(String str, String str2, int i, byte[] bArr) {
            BBDevice bBDevice = BBDevice.this;
            bBDevice.logi("scanned device name=" + str2);
            BBDevice.this.mDeviceDiscovered = true;
            synchronized (BBDevice.this.mLock) {
                BBDevice.this.mLock.notifyAll();
            }
        }
    };
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onCharacteristicWrite(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt bluetoothGatt, int i, int i2) {
            if (i == 0) {
                BBDevice.this.handleConnectionStateChanged(bluetoothGatt, i2);
            } else {
                BBDevice bBDevice = BBDevice.this;
                bBDevice.loge("Connection state change error: " + i + " newState: " + i2);
                BBDevice.this.mErrorState = i | 1024;
                BBDevice.this.handleConnectionFailed(bluetoothGatt, i2);
            }
            if (i2 == 2) {
                BBDevice unused = BBDevice.sConnectedDevice = BBDevice.this;
            } else if (i2 != 0) {
            } else {
                BBDevice unused2 = BBDevice.sConnectedDevice = null;
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
            int i2 = BBDevice.this.mAction;
            if (i == 0) {
                BBDevice.this.logi("Services discovered");
                BBDevice.this.mConnectionState = -3;
            } else {
                BBDevice bBDevice = BBDevice.this;
                bBDevice.loge("Service discovery error: " + i);
                BBDevice.this.mConnectionState = 0;
            }
            BBDevice.this.sendBroadcast(i2, 0);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt bluetoothGatt, BluetoothGattDescriptor bluetoothGattDescriptor, int i) {
            if (i == 0) {
                if (BBDevice.CLIENT_CHARACTERISTIC_CONFIG.equals(bluetoothGattDescriptor.getUuid())) {
                    BBDevice bBDevice = BBDevice.this;
                    boolean z = true;
                    if (bluetoothGattDescriptor.getValue()[0] != 1) {
                        z = false;
                    }
                    bBDevice.mNotificationsEnabled = z;
                    BBDevice bBDevice2 = BBDevice.this;
                    bBDevice2.logi("descriptor enable=" + String.valueOf(BBDevice.this.mNotificationsEnabled));
                    BBDevice.this.mErrorState = 0;
                }
            } else {
                BBDevice bBDevice3 = BBDevice.this;
                bBDevice3.loge("Descriptor write error: " + i);
                BBDevice.this.mErrorState = i | 1024;
            }
            if (BBDevice.this.mAction == 4) {
                int i2 = BBDevice.this.mAction;
                BBDevice bBDevice4 = BBDevice.this;
                bBDevice4.sendBroadcast(i2, bBDevice4.mErrorState);
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            synchronized (BBDevice.this.mLock) {
                BBDevice.this.mCurData = bluetoothGattCharacteristic.getValue();
            }
            BBDevice.this.sendBroadcast(5, 0);
        }
    };
    private volatile int mAction = -1;
    private boolean mAutoConnect = false;
    private volatile int mConnectionState = 0;

    public enum ActionType {
        ACTION_READ(0),
        ACTION_WRITE(1);
        
        private int mValue;

        ActionType(int i) {
            this.mValue = i;
        }

        int intValue() {
            return this.mValue;
        }
    }

    public static boolean isConnected() {
        return sConnectedDevice != null;
    }

    public BBDevice(Context context) {
        this.mContext = context;
        initialize(context);
    }

    public int getConnectionState() {
        return this.mConnectionState;
    }

    public boolean connect(final String str, boolean z, BBDeviceCallbacks bBDeviceCallbacks) {
        if (this.mConnectionState == -1 || this.mConnectionState == -2 || this.mConnectionState == -3) {
            return false;
        }
        this.mDeviceCallback = bBDeviceCallbacks;
        this.mAutoConnect = z;
        this.mAsyncHandler.post(new Runnable() {
            @Override
            public void run() {
                BBDevice.this._connect(str);
            }
        });
        return true;
    }

     public void _connect(String str) {
        this.mConnectionState = -1;
        this.mAction = 0;
        disconnectGatt();
        closeBluetoothGatt();
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this.mContext);
        localBroadcastManager.unregisterReceiver(this.mReceiver);
        localBroadcastManager.registerReceiver(this.mReceiver, makeIntentFilter());
        if (mNeedScan) {
            this.mBluetoothAdapter.startLeScan(this.mLeScanCallback);
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.mBluetoothAdapter.stopLeScan(this.mLeScanCallback);
            mNeedScan = false;
        }
        logi("Connecting to the device..." + str + ",thread id=" + Thread.currentThread().getId());
        BluetoothDevice remoteDevice = this.mBluetoothAdapter.getRemoteDevice(str);
        this.mBluetoothDevice = remoteDevice;
        if (remoteDevice != null) {
            logi("connectGatt...");
            BluetoothGatt connectGatt = this.mBluetoothDevice.connectGatt(this.mContext, this.mAutoConnect, this.mGattCallback);
            this.mBluetoothGatt = connectGatt;
            if (connectGatt == null) {
                loge("connectGatt failed");
                this.mConnectionState = 0;
                sendBroadcast(this.mAction, 272);
                this.mAction = -1;
            }
        } else {
            loge("get remote device error: address=" + str);
            this.mConnectionState = 0;
            sendBroadcast(this.mAction, 272);
            this.mAction = -1;
        }
        logi("connecting successfully");
    }

    private IntentFilter makeIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BBDEVICE_BROADCAST_PROGRESS);
        intentFilter.addAction(BBDEVICE_BROADCAST_CONNECTION);
        return intentFilter;
    }

    public boolean disconnect() {
        if (this.mConnectionState == 0) {
            return false;
        }
        this.mAsyncHandler.post(new Runnable() {
            @Override
            public void run() {
                BBDevice.this._disconnect();
            }
        });
        return true;
    }

    public void _disconnect() {
        if (this.mConnectionState == -4) {
            closeBluetoothGatt();
            this.mConnectionState = 0;
            sendBroadcast(1, 272);
            return;
        }
        if (this.mConnectionState == -1) {
            logi("during connecting, wait...");
            waitUntilConnected(3);
        }
        logi("Start disconnecting,thread id=" + String.valueOf(Thread.currentThread().getId()));
        this.mConnectionState = -4;
        if (this.mAction != -1 && this.mAction != 0) {
            logi("disconnect bbcp manager");
            BbcpManager bbcpManager = getBbcpManager();
            bbcpManager.disconnect();
            bbcpManager.closeBluetoothGatt();
        }
        this.mAction = 1;
        logi("Disconnecting to the device...");
        if (this.mBluetoothGatt != null) {
            BluetoothDevice bluetoothDevice = this.mBluetoothDevice;
            if (bluetoothDevice != null) {
                int connectionState = this.mBluetoothManager.getConnectionState(bluetoothDevice, 7);
                logi("bluetoothManager connect state=" + connectionState);
                if (connectionState == 2 || connectionState == 1) {
                    logi("gatt disconnect");
                    disconnectGatt();
                    waitUntilDisconnected(2);
                }
            } else {
                loge("null bluetooth device");
                sendBroadcast(1, 272);
            }
            closeBluetoothGatt();
            this.mConnectionState = 0;
            sendBroadcast(this.mAction, this.mErrorState);
            logi("bluetooth gatt disconnect()");
            return;
        }
        loge("null bluetooth gatt");
        sendBroadcast(1, 272);
    }

    public void updateSoftware(final String str, final Uri uri) {
        closeDfuManager();
        getDfuManager().setGattCallbacks(this, this.mContext);
        final String name = this.mBluetoothDevice.getName();
        refreshDeviceCache(this.mBluetoothGatt);
        this.mAsyncHandler.post(new Runnable() {
            @Override
            public void run() {
                BBDevice.this._updateSoftware(str, uri, name);
            }
        });
    }

    private void closeDfuManager() {
        DfuManager dfuManager = this.mDfuManager;
        if (dfuManager != null) {
            dfuManager.close();
            this.mDfuManager = null;
        }
    }

    public void _updateSoftware(String str, Uri uri, String str2) {
        this.mAction = 2;
        String address = this.mBluetoothDevice.getAddress();
        logi("_updateSoftware, name=" + str2 + ", address=" + address);
        if (str2 == null || !str2.equals(BOOTLOADER_NAME)) {
            logi("starting bbcp to reset device");
            BbcpManager bbcpManager = getBbcpManager();
            bbcpManager.connect(this.mContext, this.mBluetoothDevice);
            bbcpManager.sendCommand(new BbcpCommand((byte) 0, (byte) 9, createSeqNo()));
            logi("waiting for disconnection");
            waitUntilDisconnected();
            bbcpManager.disconnect();
            bbcpManager.closeBluetoothGatt();
            logi("clean the cache of gatt...");
            refreshDeviceCache(this.mBluetoothGatt);
            this.mBluetoothGatt.close();
            this.mBluetoothDevice = null;
            logi("Scanning the device...");
            this.mDeviceDiscovered = false;
            BBDeviceAdapter adapter = getAdapter();
            adapter.startScanDeviceWithAddress(null, this.scanCallbacks, address);
            waitUntilDeviceDiscovered();
            adapter.stopScanDevice();
            this.mBluetoothDevice = this.mBluetoothAdapter.getRemoteDevice(address);
        }
        logi("starting dfu manager: device name=" + this.mBluetoothDevice.getName());
        DfuManager dfuManager = getDfuManager();
        dfuManager.connect(this.mContext, this.mBluetoothDevice);
        dfuManager.uploadFirmware(str, uri);
        dfuManager.disconnect();
        dfuManager.closeBluetoothGatt();
    }

    public void bind(final String str) {
        if (!isReady()) {
            sendBroadcast(7, this.mErrorState);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._bind(str);
                }
            });
        }
    }

    public void _bind(String str) {
        this.mAction = 3;
        BbcpManager bbcpManager = getBbcpManager();
        int connect = bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        if (connect != 0) {
            sendBroadcast(7, connect);
            return;
        }
        try {
            logi("write user address: " + str);
            BbcpCommand createUserAddressCommand = BbcpCommand.createUserAddressCommand(createSeqNo(), str);
            this.mResponse = null;
            this.mErrorState = 0;
            bbcpManager.sendCommand(createUserAddressCommand);
            logi("waiting for response");
            byte[] readResponse = readResponse();
            if (readResponse == null) {
                if (this.mErrorState != 256) {
                    this.mErrorState = 269;
                }
                sendBroadcast(7, this.mErrorState);
            } else if (this.mErrorState == 0 && readResponse[0] == 2) {
                logi("read device info");
                this.mResponse = null;
                this.mErrorState = 0;
                bbcpManager.requestData(new BbcpCommand((byte) 0, (byte) 6, createSeqNo()));
                logi("waiting for response of device info");
                byte[] readResponse2 = readResponse();
                if (readResponse2 == null) {
                    loge("response is null for device info");
                    if (this.mErrorState != 256) {
                        this.mErrorState = BleManager.ERROR_RESPONSE_DEVICE_INFO;
                    }
                }
                int i = this.mErrorState;
                if (i == 0) {
                    if (setDeviceInfo(readResponse2)) {
                        sendBroadcast(7, this.mErrorState);
                    }
                } else {
                    sendBroadcast(7, i);
                }
            } else {
                logi("bind error: statusCode=" + String.valueOf((int) readResponse[0]));
                sendBroadcast(7, readResponse[0] | 512);
            }
            bbcpManager.disconnect();
            bbcpManager.closeBluetoothGatt();
        } catch (BbcpValidationException unused) {
            sendBroadcast(7, 265);
        }
    }

    private boolean setDeviceInfo(byte[] bArr) {
        TreeMap<String, String> unpackAsciiPayload = BbcpData.unpackAsciiPayload(bArr);
        this.mUuid = unpackAsciiPayload.get(ProfileConstant.DEIVCE_UUID);
        this.mModel = unpackAsciiPayload.get(ProfileConstant.DEIVCE_MODULE_NAME);
        this.mVersion = unpackAsciiPayload.get(ProfileConstant.DEIVCE_IMAGE_VESION);
        this.mCapability = unpackAsciiPayload.get(ProfileConstant.DEIVCE_CAPABILITY);
        logi("uuid=" + this.mUuid);
        logi("model=" + this.mModel);
        logi("version=" + this.mVersion);
        return true;
    }

    private byte[] readResponse() {
        try {
            synchronized (this.mLock) {
                while (this.mConnectionState != 0 && this.mResponse == null && this.mErrorState == 0) {
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
        if (this.mConnectionState == 0) {
            this.mErrorState = 256;
        }
        return this.mResponse;
    }

    public void readProfile() {
        if (!isReady()) {
            sendBroadcast(15, this.mErrorState, ActionType.ACTION_READ);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this.mAction = 15;
                    BbcpManager bbcpManager = BBDevice.this.getBbcpManager();
                    int connect = bbcpManager.connect(BBDevice.this.mContext, BBDevice.this.mBluetoothDevice);
                    if (connect != 0) {
                        BBDevice bBDevice = BBDevice.this;
                        bBDevice.sendBroadcast(bBDevice.mAction, connect);
                        return;
                    }
                    bbcpManager.requestData(new BbcpCommand((byte) 0, (byte) 13, BBDevice.this.createSeqNo(), null));
                    bbcpManager.disconnect();
                    bbcpManager.closeBluetoothGatt();
                }
            });
        }
    }

    public void writeProfile(final TreeMap<String, String> treeMap) {
        if (!isReady()) {
            sendBroadcast(8, this.mErrorState, ActionType.ACTION_WRITE);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._writeProfile(treeMap);
                }
            });
        }
    }

    public void _writeProfile(TreeMap<String, String> treeMap) {
        this.mAction = 8;
        BbcpManager bbcpManager = getBbcpManager();
        int connect = bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        if (connect != 0) {
            sendBroadcast(this.mAction, connect);
            return;
        }
        bbcpManager.sendData(BbcpCommand.createWriteProfileCommand(createSeqNo()), treeMap);
        bbcpManager.disconnect();
        bbcpManager.closeBluetoothGatt();
    }

    public void writeServeree(final String str, final int i) {
        if (!isReady()) {
            sendBroadcast(16, this.mErrorState, ActionType.ACTION_WRITE);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._writeServeree(str, i);
                }
            });
        }
    }

    public void _writeServeree(String str, int i) {
        this.mAction = 16;
        BbcpManager bbcpManager = getBbcpManager();
        int connect = bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        if (connect != 0) {
            sendBroadcast(this.mAction, connect);
            return;
        }
        bbcpManager.sendFile(new BbcpCommand((byte) 0, (byte) 14, createSeqNo(), null), str, BbcpData.intToBytes(i), this.mWritePacketsOfFlowControl);
        bbcpManager.disconnect();
        bbcpManager.closeBluetoothGatt();
    }

    public void writeAlarmSettings(final AlarmSettings alarmSettings) {
        if (!isReady()) {
            sendBroadcast(9, this.mErrorState, ActionType.ACTION_WRITE);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._writeAlarmSettings(alarmSettings);
                }
            });
        }
    }

    public void _writeAlarmSettings(AlarmSettings alarmSettings) {
        this.mAction = 9;
        BbcpManager bbcpManager = getBbcpManager();
        int connect = bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        if (connect != 0) {
            sendBroadcast(this.mAction, connect);
            return;
        }
        try {
            bbcpManager.sendData(BbcpCommand.createWriteAlarmSettingsCommand(createSeqNo()), alarmSettings.getBbcpData());
            bbcpManager.disconnect();
            bbcpManager.closeBluetoothGatt();
        } catch (BbcpValidationException e) {
            e.printStackTrace();
        }
    }

    public void readLogData(final Date date) {
        if (!isReady()) {
            sendBroadcast(10, this.mErrorState, ActionType.ACTION_READ);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._readLogData(date);
                }
            });
        }
    }

    public void _readLogData(Date date) {
        this.mAction = 10;
        BbcpManager bbcpManager = getBbcpManager();
        int connect = bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        if (connect != 0) {
            sendBroadcast(this.mAction, connect);
            return;
        }
        try {
            bbcpManager.requestData(BbcpCommand.createReadLogDataCommand(createSeqNo(), date));
            bbcpManager.disconnect();
            bbcpManager.closeBluetoothGatt();
        } catch (BbcpValidationException e) {
            e.printStackTrace();
        }
    }

    public void writeSyncTime(final int i, final short s) {
        if (!isReady()) {
            sendBroadcast(11, this.mErrorState, ActionType.ACTION_WRITE);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._writeSyncTime(i, s);
                }
            });
        }
    }

    public void _writeSyncTime(int i, short s) {
        this.mAction = 11;
        byte[] bArr = new byte[6];
        System.arraycopy(BbcpData.intToBytes(i), 0, bArr, 0, 4);
        bArr[5] = (byte) (s & 255);
        bArr[4] = (byte) (((short) (s >> 8)) & 255);
        BbcpManager bbcpManager = getBbcpManager();
        int connect = bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        if (connect != 0) {
            sendBroadcast(this.mAction, connect);
            return;
        }
        bbcpManager.sendCommand(new BbcpCommand((byte) 0, (byte) 10, createSeqNo(), bArr));
        bbcpManager.disconnect();
        bbcpManager.closeBluetoothGatt();
    }

    public void readDeviceStatus() {
        if (!isReady()) {
            sendBroadcast(12, this.mErrorState, ActionType.ACTION_READ);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._readDeviceStatus();
                }
            });
        }
    }

    public void _readDeviceStatus() {
        this.mAction = 12;
        BbcpManager bbcpManager = getBbcpManager();
        bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        bbcpManager.sendCommand(new BbcpCommand((byte) 0, (byte) 7, createSeqNo()));
        bbcpManager.disconnect();
        bbcpManager.closeBluetoothGatt();
    }

    public void readLogFileList() {
        if (!isReady()) {
            sendBroadcast(13, this.mErrorState, ActionType.ACTION_READ);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._readLogFileList();
                }
            });
        }
    }

    public void _readLogFileList() {
        this.mAction = 13;
        BbcpManager bbcpManager = getBbcpManager();
        int connect = bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        if (connect != 0) {
            sendBroadcast(this.mAction, connect);
            return;
        }
        bbcpManager.requestData(new BbcpCommand((byte) 0, (byte) 11, createSeqNo(), null));
        bbcpManager.disconnect();
        bbcpManager.closeBluetoothGatt();
    }

    public void readLogFile(final int i, final byte b) {
        if (!isReady()) {
            sendBroadcast(14, this.mErrorState, ActionType.ACTION_READ);
        } else {
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    BBDevice.this._readLogFile(i, b);
                }
            });
        }
    }

    public void _readLogFile(int i, byte b) {
        this.mAction = 14;
        BbcpManager bbcpManager = getBbcpManager();
        int connect = bbcpManager.connect(this.mContext, this.mBluetoothDevice);
        if (connect != 0) {
            sendBroadcast(this.mAction, connect);
            return;
        }
        logi("read file id=" + i + ", type=" + (int) b);
        bbcpManager.requestData(BbcpCommand.createReadLogFileCommand(createSeqNo(), i, b), this.mReadPacketsOfFlowControl);
        bbcpManager.disconnect();
        bbcpManager.closeBluetoothGatt();
    }

    public void setFlowControlPackets(short s, short s2) {
        this.mReadPacketsOfFlowControl = s;
        this.mWritePacketsOfFlowControl = s2;
    }

    public boolean abort() {
        if (this.mAction == -1) {
            logi("abort none");
            this.mAsyncHandler.removeCallbacksAndMessages(null);
            return false;
        }
        getBbcpManager().abortTask();
        return true;
    }

    public String getId() {
        return this.mUuid;
    }

    public String getVersion() {
        return this.mVersion;
    }

    public String getModel() {
        return this.mModel;
    }

    public BBDeviceAdapter getAdapter() {
        if (this.mAdapter == null) {
            this.mAdapter = new BBDeviceAdapter(this.mBluetoothAdapter, this.mContext);
        }
        return this.mAdapter;
    }

    public void handleConnectionStateChanged(final BluetoothGatt bluetoothGatt, int i) {
        if (i == 2) {
            logi("Connected to GATT server");
            this.mConnectionState = -2;
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    boolean discoverServices = bluetoothGatt.discoverServices();
                    BBDevice bBDevice = BBDevice.this;
                    StringBuilder sb = new StringBuilder();
                    sb.append("Attempting to start service discovery...");
                    sb.append(discoverServices ? "succeed" : "failed"/*e.b*/);
                    bBDevice.logi(sb.toString());
                    if (!discoverServices) {
                        BBDevice.this.loge("discover services failed");
                        BBDevice.this.mErrorState = 261;
                    }
                }
            });
        } else if (i == 0) {
            logi("Disconnected from GATT server");
            this.mConnectionState = 0;
            if (this.mAction == 2) {
                logi("device reset");
                synchronized (this.mLock) {
                    this.mLock.notifyAll();
                }
            } else if (this.mAction == 1) {
                this.mErrorState = 0;
                synchronized (this.mLock) {
                    this.mLock.notifyAll();
                }
            } else {
                disconnectGatt();
                closeBluetoothGatt();
                sendBroadcast(-1, 0);
            }
        }
    }

    private boolean initialize(Context context) {
        if (this.mBluetoothManager == null) {
            BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            this.mBluetoothManager = bluetoothManager;
            if (bluetoothManager == null) {
                loge("Unable to initialize BluetoothManager.");
                return false;
            }
        }
        BluetoothAdapter adapter = this.mBluetoothManager.getAdapter();
        this.mBluetoothAdapter = adapter;
        if (adapter == null) {
            loge("Unable to obtain a BluetoothAdapter.");
            return false;
        }
        getBbcpManager().setGattCallbacks(this, context);
        HandlerThread handlerThread = new HandlerThread(TAG);
        handlerThread.start();
        this.mAsyncLooper = handlerThread.getLooper();
        this.mAsyncHandler = new Handler(this.mAsyncLooper);
        return true;
    }

    protected void handleConnectionFailed(BluetoothGatt bluetoothGatt, int i) {
        if (this.mAction == 0) {
            logi("handleConnectionFailed");
            this.mConnectionState = 0;
            closeBluetoothGatt();
            sendBroadcast(this.mAction, this.mErrorState);
        } else if (this.mAction != 1) {
        } else {
            synchronized (this.mLock) {
                this.mLock.notifyAll();
            }
        }
    }

    public void loge(String str) {
        Log.e(TAG, str);
    }

    private void loge(String str, Throwable th) {
        Log.e(TAG, str, th);
    }

    public void logi(String str) {
        Log.i(TAG, str);
    }

    private DfuManager getDfuManager() {
        if (this.mDfuManager == null) {
            this.mDfuManager = new DfuManager();
        }
        return this.mDfuManager;
    }

    public BbcpManager getBbcpManager() {
        if (this.mBbcpManager == null) {
            this.mBbcpManager = new BbcpManager();
        }
        return this.mBbcpManager;
    }

    private void sendConnectBroadcast(int i) {
        Intent intent = new Intent(BBDEVICE_BROADCAST_CONNECTION);
        intent.putExtra(EXTRA_CONNECTION_STATE, i);
        LocalBroadcastManager.getInstance(this.mContext).sendBroadcast(intent);
    }

    private void sendBroadcast(int i, int i2, ActionType actionType) {
        Intent intent = new Intent(BBDEVICE_BROADCAST_PROGRESS);
        intent.putExtra("status", i2);
        intent.putExtra("action", i);
        intent.putExtra(EXTRA_ACTION_TYPE, actionType.intValue());
        LocalBroadcastManager.getInstance(this.mContext).sendBroadcast(intent);
    }

    public void sendBroadcast(int i, int i2) {
        Intent intent = new Intent(BBDEVICE_BROADCAST_PROGRESS);
        intent.putExtra("status", i2);
        intent.putExtra("action", i);
        LocalBroadcastManager.getInstance(this.mContext).sendBroadcast(intent);
    }

    public byte createSeqNo() {
        byte b = (byte) (this.mSeqNo + 1);
        this.mSeqNo = b;
        byte b2 = (byte) (b % 8);
        this.mSeqNo = b2;
        return b2;
    }

    private void waitUntilDisconnected() {
        try {
            synchronized (this.mLock) {
                while (this.mConnectionState != 0) {
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
    }

    private void waitUntilConnected(int i) {
        try {
            synchronized (this.mLock) {
                while (this.mConnectionState != -2 && this.mConnectionState != -3 && i > 0) {
                    this.mLock.wait(2000L);
                    if (i > 0) {
                        i--;
                    }
                    logi(String.format("wait connect wake: connectionState=%d, error=%d, waitCount=%d", this.mConnectionState, this.mErrorState, i));
                }
                logi(String.format("wait connect leave: connectionState=%d, error=%d, waitCount=%d", this.mConnectionState, this.mErrorState, i));
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
    }

    private void waitUntilDeviceDiscovered() {
        try {
            synchronized (this.mLock) {
                while (!this.mDeviceDiscovered) {
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
    }

    private void refreshDeviceCache(BluetoothGatt bluetoothGatt) {
        try {
            Method method = bluetoothGatt.getClass().getMethod("refresh");
            if (method != null) {
                boolean booleanValue = (Boolean) method.invoke(bluetoothGatt, new Object[0]);
                logi("Refreshing result: " + booleanValue);
            }
        } catch (Exception e) {
            loge("An exception occured while refreshing device", e);
        }
    }

    public void enableLiveDataNotification(boolean z) {
        if (!isReady()) {
            sendBroadcast(4, 270);
            return;
        }
        this.mAction = 4;
        BluetoothGattService service = this.mBluetoothGatt.getService(BbcpManager.BBCP_DATA_SERVICE_UUID);
        if (service == null) {
            loge("Device has no required service");
            sendBroadcast(this.mAction, 267);
            return;
        }
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(BbcpManager.BBCP_DATA_UUID);
        if (characteristic == null) {
            loge("Device has no required characteristic");
            sendBroadcast(this.mAction, 267);
            return;
        }
        setCharacteristicNotification(this.mBluetoothGatt, characteristic, z);
    }

    private boolean isReady() {
        if (this.mConnectionState != -3) {
            loge("not connected and ready, mConnectionState=" + this.mConnectionState);
            this.mErrorState = 256;
            return false;
        } else if (this.mAction != -1) {
            loge("device is busy,action=" + this.mAction);
            this.mErrorState = 270;
            return false;
        } else {
            this.mErrorState = 0;
            return true;
        }
    }

    private void setCharacteristicNotification(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, boolean z) {
        this.mErrorState = 0;
        StringBuilder sb = new StringBuilder();
        sb.append(z ? "Enabling " : "Disabling");
        sb.append(" notifications...");
        logi(sb.toString());
        bluetoothGatt.setCharacteristicNotification(bluetoothGattCharacteristic, z);
        BluetoothGattDescriptor descriptor = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
        descriptor.setValue(z ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        bluetoothGatt.writeDescriptor(descriptor);
    }

    @Override
    public void onProgressUpdate(int i) {
        this.mDeviceCallback.onProgressUpdate(i);
    }

    @Override
    public void onDataReceived(int i, byte[] bArr, byte[] bArr2) {
        int i2 = this.mAction;
        logi("onDataReceived: operation=" + i2 + ",status=" + i);
        if (i2 == 2) {
            logi("update software response=" + (int) bArr[0]);
            if (bArr != null) {
                byte b = bArr[0];
            }
        } else if (i2 == 3 || i2 == 6) {
            this.mErrorState = i;
            this.mResponse = bArr;
            synchronized (this.mLock) {
                this.mLock.notifyAll();
            }
        } else {
            TreeMap<String, String> treeMap = null;
//            r4 = null;
            DeviceLogFileInfo[] deviceLogFileInfoArr = null;
            treeMap = null;
            treeMap = null;
            if (i2 == 13) {
                this.mAction = -1;
                if (i == 0 && bArr != null) {
                    deviceLogFileInfoArr = createFileListInfos(bArr, bArr2);
                }
                logi("onLogFileListRead() is called");
                this.mDeviceCallback.onLogFileListRead(i, deviceLogFileInfoArr);
            } else if (i2 == 11) {
                this.mAction = -1;
                if (i == 0 && bArr.length == 1 && bArr[0] != 2) {
                    i = bArr[0] | 512;
                }
                logi("onDataWrite() is called");
                this.mDeviceCallback.onDataWrite(i2, i);
            } else {
                this.mAction = -1;
                if (i2 == 15 && bArr != null && i == 0) {
                    treeMap = BbcpData.unpackAsciiPayload(bArr);
                }
                logi("onDataRead() is called");
                this.mDeviceCallback.onDataRead(i2, i, bArr, treeMap);
            }
        }
    }

    private DeviceLogFileInfo[] createFileListInfos(byte[] bArr, byte[] bArr2) {
        int i = BbcpData.toShort(bArr2, 0);
        int length = bArr.length / i;
        DeviceLogFileInfo[] deviceLogFileInfoArr = new DeviceLogFileInfo[i];
        for (int i2 = 0; i2 < i; i2++) {
            int i3 = length * i2;
            byte b = bArr[i3];
            deviceLogFileInfoArr[i2] = new DeviceLogFileInfo();
            if (b > 4) {
                i3++;
                deviceLogFileInfoArr[i2].fileId = BbcpData.toInt(bArr, i3);
            }
            if (b > 8) {
                i3 += 4;
                deviceLogFileInfoArr[i2].activityTime = BbcpData.toInt(bArr, i3);
            }
            if (b > 12) {
                i3 += 4;
                deviceLogFileInfoArr[i2].activityDistance = BbcpData.toInt(bArr, i3);
            }
            if (b > 13) {
                i3 += 4;
                deviceLogFileInfoArr[i2].isWorkout = bArr[i3] == 1;
            }
            if (b > 17) {
                i3++;
                deviceLogFileInfoArr[i2].workoutId = BbcpData.toInt(bArr, i3);
            }
            if (b > 18) {
                deviceLogFileInfoArr[i2].sportType = bArr[i3 + 4];
            }
        }
        return deviceLogFileInfoArr;
    }

    @Override
    public void onDataSend(int i) {
        int i2 = this.mAction;
        this.mAction = -1;
        this.mDeviceCallback.onDataWrite(i2, i);
    }

    @Override
    public void onUploaded(int i) {
        closeDfuManager();
        if (i == 1) {
            i = 0;
        }
        this.mDeviceCallback.onSoftwareUpdated(i);
    }

    protected void waitUntilDisconnected(int i) {
        try {
            synchronized (this.mLock) {
                while (this.mConnectionState != 0 && i > 0) {
                    this.mLock.wait(2000L);
                    if (i > 0) {
                        i--;
                    }
                    logi(String.format("wake: connectionState=%d, error=%d, waitCount=%d", this.mConnectionState, this.mErrorState, i));
                }
                if (i == 0) {
                    loge("disconnect timeout");
                }
                logi(String.format("leave: connectionState=%d, error=%d, waitCount=%d", this.mConnectionState, this.mErrorState, i));
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
    }

    private synchronized void closeBluetoothGatt() {
        logi("Cleaning up...");
        sConnectedDevice = null;
        BluetoothGatt bluetoothGatt = this.mBluetoothGatt;
        if (bluetoothGatt != null) {
            bluetoothGatt.close();
            this.mBluetoothGatt = null;
        }
    }

    private synchronized void disconnectGatt() {
        sConnectedDevice = null;
        BluetoothGatt bluetoothGatt = this.mBluetoothGatt;
        if (bluetoothGatt != null) {
            bluetoothGatt.disconnect();
        }
    }
}
